# -*- coding: utf-8 -*-
"""
# --------------------------------------------------------
# @Author : Pan
# @E-mail : 
# @Date   : 2025-11-17 15:28:37
# @Brief  :
# --------------------------------------------------------
"""
import numpy as np
import PIL.Image as Image

from pybaseutils import file_utils, json_utils


def gradio2openai_style(msgs: list or dict):
    """
    gradio风格转换为openai风格
    gradio messages is [
             {'role': 'user/assistant', 'content': "用户问题/任务描述"},
             {'role': 'user/assistant', 'content': [image_file]},
             {'role': 'user/assistant', 'content': [video_file]},
         ]
    openai messages is [
         {'role': 'user/assistant', 'content': [{"type": "text", "text": "用户问题/任务描述"}]},
         {'role': 'user/assistant', 'content': [{"type": "image", "image": image_file}]},
         {'role': 'user/assistant', 'content': [{"type": "video", "video": [f1,f2,f3]}]},
         ]
    :param msgs:
    :return:
    """
    if not msgs: return msgs
    isdict = isinstance(msgs, dict)
    if isdict: msgs = [msgs]
    out = []
    for msg in msgs:
        content, role = msg["content"], msg["role"]
        if isinstance(content, str):
            content = [{"type": "text", "text": content}]
        elif isinstance(content, list):
            # if len(content) == 1:
            #     content = [{"type": "image", "image": content[0]}]
            # elif len(content) > 1:
            #     content = [{"type": "video", "video": content}]
            content = [{"type": "image_url", "image_url": {"url": c}} for c in content]
        if out and out[-1]["role"] == role:  # 合并相邻相同角色的消息
            out[-1]["content"].extend(content)
        else:
            out.append({**msg, "content": content})
    if isdict: out = out[0]
    return out


def openai2gradio_style(msgs):
    """
    openai风格转换为gradio风格
    :param msgs:
    :return:
    """
    if not msgs: return msgs
    isdict = isinstance(msgs, dict)
    if isdict: msgs = [msgs]
    out = []
    for msg in msgs:
        content, role = msg["content"], msg["role"]
        if isinstance(content, list):  # 合并相邻相同角色的消息
            for c in content:
                if c["type"] == "text":
                    out.append({**msg, "role": role, "content": c["text"]})
                elif c["type"] == "image":
                    out.append({**msg, "role": role, "content": [c["image"]]})
                elif c["type"] == "video":
                    out.append({**msg, "role": role, "content": c["video"]})
                else:
                    out.append({**msg, "role": role, "content": c})
        else:
            out.append({**msg, "content": content})
    if isdict: out = out[0]
    return out


def flatten(data):
    """
    展开列表
    :param data:
    :return:
    """
    out = []
    for item in data:
        if isinstance(item, list):
            out.extend(flatten(item))
        else:
            out.append(item)
    return out


if __name__ == "__main__":
    image_file = "/media/PKing/dev2/SDK/base-utils/data/mask.png"
    image = Image.open(image_file)
    msgs = [{"role": "user", "content": "你好", "time": (0, 1)},
            {"role": "assistant", "content": "你好，有什么我可以帮助你的吗？", "time": (1, 2)},
            {"role": "user", "content": [image, image, image], "time": (2, 3)},
            {"role": "user", "content": "请根据图片描述", "time": (3, 4)},
            {"role": "assistant", "content": "这张图是描述.....", "time": (4, 5)},
            ]
    out1 = gradio2openai_style(msgs)
    out2 = openai2gradio_style(out1)
    print(json_utils.formatting(out2))
